package com.bjtime.designer.widget

import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.AbsoluteLayout
import com.bjtime.designer.attributes.BaseAttr
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import android.view.ViewTreeObserver
import com.bjtime.designer.attributes.ViewAttr
import com.bjtime.designer.utils
import java.io.File
import java.lang.Exception
import java.lang.RuntimeException
import java.lang.reflect.Method


class AbsDesignerLayout : AbsoluteLayout , View.OnTouchListener {

    var xDelta: Int = 0
    var yDelta: Int = 0
    var mNowView : BaseLabelView? = null
    var listener : onViewSelect? = null;
    var mChildCount = 0
    interface onViewSelect {
        fun onSelect (v: BaseLabelView?) {
            v.toString ()
        }
    }

    fun setSelectListener (l: onViewSelect) {
        listener = l;
    }

    constructor(context: Context) : this(context, null as AttributeSet)
    constructor(context: Context, attrs: AttributeSet) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        setOnClickListener({_->
            if (mNowView != null) {
                mNowView?.setSelect(false);
                mNowView = null;
            }
            if(listener != null)
                listener?.onSelect(null);
        })

    }

    var DES_SPAC : Int = 0
    fun setSpac (spac : Int) {
        DES_SPAC = spac
        for (index in 0 until  childCount) {
            (getChildAt(index) as BaseLabelView)!!.onMoved(spac)
        }
    }


    override fun removeView(view: View?) {
        if (view == null)
            return;
        super.removeView(view);
        mChildCount--
        ReSetIds ();
    }

    override fun onViewAdded(child: View) {
        if (child !is BaseLabelView) {
            throw Exception ("标签设计布局器禁止添加其他类型组件~\n需求组件类型：BaseLabelView->\n实际添加类型："+child!!.toString())
            return
        }
        child.setOnTouchListener(this)
        mChildCount++
        if ((child as BaseLabelView).des_id == -1) {
            ReSetIds ()
            if (child.des_width != 0 && child.des_height != 0) {
                update(child)
            } else if (child.des_viewtype == ViewAttr.VIEW_TYPE.QRCODE || child.des_viewtype == ViewAttr.VIEW_TYPE.IMAGE) {
                var params = child.layoutParams
                params.height = utils.dp2px(context, 60f)
                params.width = utils.dp2px(context, 60f)
                child.layoutParams = params
            } else if (child.des_viewtype == ViewAttr.VIEW_TYPE.BARCODE) {
                var params = child.layoutParams
                params.height = utils.dp2px(context, 70f)
                params.width = utils.dp2px(context, 150f)
                child.layoutParams = params
            }
        } else {
            update(child)
        }
        child.prepared()
    }

    fun ReSetIds () {
        for (i in 0..childCount-1) {
            (getChildAt(i) as BaseLabelView).des_id = i
        }
    }


    override fun onTouch(v: View, event: MotionEvent): Boolean {
        val x = event.rawX.toInt()
        val y = event.rawY.toInt()
        when (event.action and MotionEvent.ACTION_MASK) {

            MotionEvent.ACTION_DOWN -> {
                xDelta = x - v.left
                yDelta = y - v.top
                if (v is BaseLabelView) {
                    if (mNowView != null || mNowView != v) {
                        mNowView?.setSelect(false)
                    }
                    v.requestDisallowInterceptTouchEvent (true);
                    v.setSelect(true)
                    v.bringToFront ()
                }
            }

            MotionEvent.ACTION_MOVE -> {
                if ((v as BaseLabelView).getAttr().des_lock)
                    return false
                val layoutParams = v.layoutParams as AbsoluteLayout.LayoutParams
                val xDistance = x - xDelta
                val yDistance = y - yDelta

                layoutParams.x = xDistance
                layoutParams.y = yDistance
                v.layoutParams = layoutParams
                v.onMoved (DES_SPAC)
            }

            MotionEvent.ACTION_UP->{
                if (v is BaseLabelView) {
                    v.requestDisallowInterceptTouchEvent (false);
                }
                if(mNowView != v || v != null) {
                    mNowView = v as BaseLabelView
                    if (listener != null)
                        listener?.onSelect(v)
                }
            }
        }
        return true
    }



    fun getSelectEle () : BaseLabelView? {
        return if (mNowView == null)  null else mNowView
    }

    fun deleteEle (ele : BaseLabelView, isMove : Boolean) {
        var mId : Int = ele.des_id
        removeView(ele)
        mNowView = null
        if (isMove) {
            if (childCount != 0) {
                mNowView?.setSelect(false)
                mNowView = getChildAt(childCount - 1) as BaseLabelView
                mNowView?.setSelect(true)
                if (listener != null)
                    listener?.onSelect(mNowView)
            }
        }
    }

    fun setSelectEle(v : BaseLabelView?) {
        if (childCount == 0 || v == null)
            return
        if (getSelectEle () == null) {
            v.setSelect(true)
            mNowView = v
            if (listener != null)
                listener?.onSelect(mNowView)
        } else {
            mNowView!!.setSelect(false)
            mNowView = v
            mNowView!!.setSelect(true)
            if (listener != null)
                listener?.onSelect(mNowView)
        }
    }

    fun getAllLabel () : List<BaseAttr> {
        var list = ArrayList <BaseAttr> ()
        for (i in 0 until childCount) {
            if (getChildAt(i) is BaseLabelView)
                list.add((getChildAt(i) as BaseLabelView).getAttr())
        }
        return list
    }

    fun getAllLabelView () : List<BaseLabelView> {
        var list = ArrayList <BaseLabelView> ()
        for (i in 0 until childCount) {
            if (getChildAt(i) is BaseLabelView)
                list.add((getChildAt(i) as BaseLabelView))
        }
        return list
    }

    fun addView(child: BaseLabelView, attr:BaseAttr) {
        child.setAttr (attr)
        super.addView(child)
    }

    override fun addView(child: View?, index: Int, params: ViewGroup.LayoutParams?) {
        if (child !is BaseLabelView) {
            throw Exception ("标签设计布局器禁止添加其他类型组件~\n需求组件类型：BaseLabelView->\n实际添加类型："+child!!.toString())
            return
        }
        super.addView(child, index, params)
        setSelectEle(child)
        if (listener != null)
            listener?.onSelect(child)
    }

    open fun update (view : BaseLabelView) {
        var params = view.layoutParams as AbsoluteLayout.LayoutParams
        if (view.des_viewtype == ViewAttr.VIEW_TYPE.TEXT) {

        } else if (view.des_viewtype == ViewAttr.VIEW_TYPE.LINE){
            params.width = view.des_width
            params.height = -2
        } else {
            params.width = view.des_width
            params.height = view.des_height
        }
        params.x = view.des_left - 3
        params.y = view.des_top  - 3
        view.layoutParams = params
    }

    fun addLabel (type : ViewAttr.VIEW_TYPE,content:String) {
        when (type) {
            ViewAttr.VIEW_TYPE.TEXT     ->  { addView (TextView2 (context,content)) }
            ViewAttr.VIEW_TYPE.IMAGE    ->  { addView (ImageView2 (context, File (content).readBytes()))}
            ViewAttr.VIEW_TYPE.BARCODE  ->  { addView (BarCodeView2 (context,content))}
            ViewAttr.VIEW_TYPE.QRCODE   ->  { addView (QRCodeView2 (context,content))}
            ViewAttr.VIEW_TYPE.LINE     ->  { addView (LineView2 (context))}
            ViewAttr.VIEW_TYPE.RECT     ->  {}
            ViewAttr.VIEW_TYPE.TABLE    ->  {}
            ViewAttr.VIEW_TYPE.BASE     ->  {}
        }
    }


}